// src/page/AuthorityPage.tsx
import React, {useContext, useEffect, useState} from 'react';
import {
    Table,
    Button,
    Typography,
    Spin,
    Alert,
    Modal,
    Form,
    Input,
    Select,
    Space,
    message,
    Card,
    Row,
    Col
} from 'antd';
import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    ReloadOutlined
} from '@ant-design/icons';
import sysAuthContext from '../context/SysAuthContext';
import type { Role, Authority } from '../api/service/SysAuthService.tsx';

const { Title } = Typography;
const { Option } = Select;

const AuthorityPage: React.FC = () => {

    const useSysAuth = useContext(sysAuthContext);

    if (!useSysAuth) {
        throw new Error('useSysAuth must be used within a sysAuthProvider');
    }

    const {
        roles,
        authorities,
        loadingRoles,
        loadingAuthorities,
        fetchRoles,
        fetchAuthorities,
        createRole,
        updateRole,
        deleteRole,
        error,
        clearError
    } = useSysAuth;

    const [isModalVisible, setIsModalVisible] = useState(false);
    const [editingRole, setEditingRole] = useState<Role | null>(null);
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);

    // 组件挂载时获取数据
    useEffect(() => {
        fetchRoles();
        fetchAuthorities();
    }, [fetchRoles, fetchAuthorities]);

    // 处理错误信息
    useEffect(() => {
        if (error) {
            message.error(error);
            clearError();
        }
    }, [error, clearError]);

    // 处理添加角色
    const handleAddRole = () => {
        setEditingRole(null);
        form.resetFields();
        setIsModalVisible(true);
    };

    // 处理编辑角色
    const handleEditRole = (role: Role) => {
        setEditingRole(role);
        form.setFieldsValue({
            roleName: role.roleName,
            authorityIds: role.authorities.map(auth => auth.id)
        });
        setIsModalVisible(true);
    };

    // 处理删除角色
    const handleDeleteRole = async (id: string) => {
        try {
            const result = await deleteRole(id);
            if (result) {
                message.success('角色删除成功');
            } else {
                message.error('角色删除失败');
            }
        } catch (err) {
            message.error('角色删除失败: ' + (err instanceof Error ? err.message : '未知错误'));
        }
    };

    // 处理表单提交
    const handleFormSubmit = async (values: { roleName: string; authorityIds: string[] }) => {
        setLoading(true);
        try {
            if (editingRole) {
                // 更新角色
                const result = await updateRole({
                    id: editingRole.id,
                    roleName: values.roleName,
                    authorityIds: values.authorityIds
                });

                if (result) {
                    message.success('角色更新成功');
                    setIsModalVisible(false);
                    form.resetFields();
                } else {
                    message.error('角色更新失败');
                }
            } else {
                // 创建角色
                const result = await createRole({
                    roleName: values.roleName,
                    authorityIds: values.authorityIds
                });

                if (result) {
                    message.success('角色创建成功');
                    setIsModalVisible(false);
                    form.resetFields();
                } else {
                    message.error('角色创建失败');
                }
            }
        } catch (err) {
            message.error((err instanceof Error ? err.message : '操作失败'));
        } finally {
            setLoading(false);
        }
    };

    // 角色表格列定义
    const roleColumns = [
        {
            title: '角色ID',
            dataIndex: 'id',
            key: 'id',
            width: 100,
        },
        {
            title: '角色名称',
            dataIndex: 'roleName',
            key: 'roleName',
        },
        {
            title: '权限列表',
            dataIndex: 'authorities',
            key: 'authorities',
            render: (authorities: Authority[]) => (
                <span>
          {authorities.map(auth => auth.authorityName).join(', ')}
        </span>
            )
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (date: string) => new Date(date).toLocaleString(),
            width: 180,
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            render: (date: string) => new Date(date).toLocaleString(),
            width: 180,
        },
        {
            title: '操作',
            key: 'action',
            width: 150,
            render: (_: unknown, record: Role) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => handleEditRole(record)}
                    >
                        编辑
                    </Button>
                    <Button
                        type="link"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => handleDeleteRole(record.id)}
                    >
                        删除
                    </Button>
                </Space>
            ),
        },
    ];

    // 权限表格列定义
    const authorityColumns = [
        {
            title: '权限ID',
            dataIndex: 'id',
            key: 'id',
            width: 100,
        },
        {
            title: '权限名称',
            dataIndex: 'authorityName',
            key: 'authorityName',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (date: string) => new Date(date).toLocaleString(),
            width: 180,
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            render: (date: string) => new Date(date).toLocaleString(),
            width: 180,
        },
    ];

    return (
        <div style={{
            height: 'calc(100vh - 112px)',
            overflowY: 'auto',
            scrollbarWidth: 'thin',
            scrollbarColor: '#c1c1c1 #f1f1f1'
        }}>
            <style>
                {`
        /* Webkit浏览器滚动条样式 */
        div::-webkit-scrollbar {
          width: 6px;
        }
        
        div::-webkit-scrollbar-track {
          background: #f1f1f1;
          border-radius: 10px;
        }
        
        div::-webkit-scrollbar-thumb {
          background: #c1c1c1;
          border-radius: 10px;
        }
        
        div::-webkit-scrollbar-thumb:hover {
          background: #a8a8a8;
        }
        `}
            </style>

            <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
                <Col>
                    <Title level={3}>权限管理</Title>
                </Col>
                <Col>
                    <Space>
                        <Button
                            icon={<ReloadOutlined />}
                            onClick={() => {
                                fetchRoles();
                                fetchAuthorities();
                            }}
                            loading={loadingRoles || loadingAuthorities}
                        >
                            刷新
                        </Button>
                        <Button
                            type="primary"
                            icon={<PlusOutlined />}
                            onClick={handleAddRole}
                            loading={loadingRoles}
                        >
                            添加角色
                        </Button>
                    </Space>
                </Col>
            </Row>

            {error && (
                <Alert
                    message="数据加载失败"
                    description={error}
                    type="error"
                    showIcon
                    style={{ marginBottom: 16 }}
                />
            )}

            <Spin spinning={loadingRoles && roles.length === 0}>
                <Card title="角色管理" style={{ marginBottom: 20 }}>
                    <Table
                        dataSource={roles}
                        columns={roleColumns}
                        rowKey="id"
                        pagination={false}
                        scroll={{ x: 800 }}

                    />
                </Card>

                <Card title="权限列表">
                    <Spin spinning={loadingAuthorities && authorities.length === 0}>
                        <Table
                            dataSource={authorities}
                            columns={authorityColumns}
                            rowKey="id"
                            pagination={false}
                            scroll={{ x: 600 }}
                        />
                    </Spin>
                </Card>
            </Spin>

            {/* 角色编辑/创建模态框 */}
            <Modal
                title={editingRole ? "编辑角色" : "创建角色"}
                open={isModalVisible}
                onCancel={() => {
                    setIsModalVisible(false);
                    form.resetFields();
                }}
                onOk={() => form.submit()}
                confirmLoading={loading}
                width={600}
            >
                <Form
                    form={form}
                    layout="vertical"
                    onFinish={handleFormSubmit}
                >
                    <Form.Item
                        name="roleName"
                        label="角色名称"
                        rules={[{ required: true, message: '请输入角色名称' }]}
                    >
                        <Input placeholder="请输入角色名称" />
                    </Form.Item>

                    <Form.Item
                        name="authorityIds"
                        label="权限列表"
                        rules={[{ required: true, message: '请选择权限' }]}
                    >
                        <Select
                            mode="multiple"
                            placeholder="请选择权限"
                            optionFilterProp="children"
                            filterOption={(input, option) =>
                                (option?.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                            }
                        >
                            {authorities.map(authority => (
                                <Option key={authority.id} value={authority.id}>
                                    {authority.authorityName}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default AuthorityPage;
